package com.cdks.wuxiu.api.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cdks.wuxiu.api.model.dto.MoodTopicInfoDTO;
import com.cdks.wuxiu.api.component.aliyun.CloudStorage;
import com.cdks.wuxiu.api.component.constant.Constant;
import com.cdks.wuxiu.api.model.dto.MoodReplyInfoDTO;
import com.cdks.wuxiu.api.model.param.MoodCommentParam;
import com.cdks.wuxiu.api.model.param.MoodTranslateParam;
import com.cdks.wuxiu.api.model.param.MoodHideTopicParam;
import com.cdks.wuxiu.api.model.param.MoodDelReplyParam;
import com.cdks.wuxiu.api.model.param.MoodDelTopicParam;
import com.cdks.wuxiu.api.model.param.MoodGetDetailParam;
import com.cdks.wuxiu.api.model.param.MoodGetTopicListParam;
import com.cdks.wuxiu.api.model.param.MoodPublishParam;
import com.cdks.wuxiu.api.model.param.MoodReportParam;
import com.cdks.wuxiu.api.model.param.MoodGetReplyListParam;
import com.cdks.wuxiu.api.model.param.MoodGetUserTopicParam;
import com.cdks.wuxiu.api.model.vo.MoodTopicListVO;
import com.cdks.wuxiu.api.model.vo.MoodDetailVO;
import com.cdks.wuxiu.api.model.vo.MoodReplyVO;
import com.cdks.wuxiu.api.model.vo.MoodTopicInfoVO;
import com.cdks.wuxiu.api.model.vo.UserInfoVO;
import com.cdks.wuxiu.api.service.AuthService;
import com.cdks.wuxiu.api.service.MoodService;
import com.cdks.wuxiu.api.service.UserService;
import com.cdks.wuxiu.api.util.SmsUtils;
import com.cdks.wuxiu.api.util.TimeUtils;
import com.cdks.wuxiu.common.component.constant.ApiCodeEnum;
import com.cdks.wuxiu.common.model.api.ApiResult;
import com.cdks.wuxiu.entity.mongodb.MoodTransInfo;
import com.cdks.wuxiu.entity.mood.TopicTypeData;
import com.cdks.wuxiu.entity.mysql.MoodReplyInfo;
import com.cdks.wuxiu.entity.mysql.MoodTopicInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.validation.Valid;


@Slf4j
@Api(tags = "用户心情")
@RestController
@RequestMapping("/mood")
public class MoodController {
    @Resource
    private MoodService moodService;
    @Resource
    private AuthService authService;
    @Resource
    private UserService userService;    
    

    private int delCloudStorage(int type, long userId, TopicTypeData data)
    {
        switch (type)
        {
            case Constant.MOOD_TYPE_ONLY_AUDIO:
            {
                for (String file : data.getFileList())
                {
                    CloudStorage.deleteMoodFile(userId, file);
                }
             
                break;
            }
            case Constant.MOOD_TYPE_TEXT_IMAGE:
            {
                for (String file : data.getFileList())
                {
                    CloudStorage.deleteMoodFile(userId, file);
                }

                break;
            }
            case Constant.MOOD_TYPE_TEXT_VIDEO:
            {
                for (String file : data.getFileList())
                {
                    CloudStorage.deleteMoodFile(userId, file);
                }
             
                break;
            }
            default:
            {
                break;
            }
        }

        return 0;
    }    

    @ApiOperation("发布心情")
    @PostMapping("/publish")
    public ApiResult<Object> publish(@RequestBody @Valid MoodPublishParam param) {
        int ret  = 0;
        String msg  = null;


        MoodTopicInfo topicInfo  = new MoodTopicInfo();
        topicInfo.setType(param.getType());
        topicInfo.setUserId(param.getUserId());
        topicInfo.setContent(param.getData());
        topicInfo.setCreateTime(TimeUtils.getTimeSecond());

        TopicTypeData data  = BeanUtil.copyProperties(JSONUtil.parseObj(param.getData()), TopicTypeData.class);
        switch (param.getType())
        {
            case Constant.MOOD_TYPE_ONLY_TEXT:
            {
                if (data.getContent().trim() == null)
                {
                    msg  = "文字内容不能为空";
                }

                break;
            }
            case Constant.MOOD_TYPE_TEXT_IMAGE:
            {
                if ((data.getContent().trim() == null) || (data.getFileList() == null))
                {
                    msg  = "文字内容或图片文件不能为空";
                }

                break;
            }
            case Constant.MOOD_TYPE_ONLY_AUDIO:
            {
                if (data.getFileList() == null)
                {
                    msg  = "文件不能为空";
                }

                break;
            }
            case Constant.MOOD_TYPE_TEXT_VIDEO:
            {
                if ((data.getContent().trim() == null) || (data.getFileList() == null))
                {
                    msg  = "文字内容或视频文件不能为空";
                }

                break;
            }
            case Constant.MOOD_TYPE_TEXT_LINK:
            {
                if ((data.getTitle() == null) || (data.getUrl() == null))
                {
                    msg  = "标题和链接不能为空";
                }

                break;
            }
            default:
            {
                msg  = "不支持的类型";

                break;
            }
        }
        
        if (msg != null)
        {
            return ApiResult.failed(10, msg);
        }

        // 保存主题记录
        ret  = moodService.saveTopic(topicInfo);
        if (ret < 0)
        {
            return ApiResult.failed(10, "发布失败，请稍后再试");
        }

        //发送短信通知
        if (param.getUserInfo().getType() == Constant.ACCOUNT_TYPE_USER)
        {
            SmsUtils.sendManageNotice("用户" + param.getUserId() + "发布了心情");
        }

        return ApiResult.success("提交成功，请等待审核"); 
    }

    @ApiOperation("评论心情")
    @PostMapping("/comment")
    public ApiResult<Object> comment(@RequestBody @Valid MoodCommentParam param) {
        MoodTopicInfo topicInfo  = moodService.getTopicById(param.getTopicId());
        if (topicInfo == null)
        {
            return ApiResult.failed(10, "当前主题不存在");
        }

        if ((topicInfo.getStatus() != Constant.AUDIT_STATUS_PASS) || (topicInfo.getIsValid() == Constant.DATA_STATUS_DISABLE))
        {
            return ApiResult.failed(10, "当前主题不可评论");
        }

        MoodReplyInfo replyInfo  = new MoodReplyInfo();
        replyInfo.setUserId(param.getUserId());
        replyInfo.setTopicId(param.getTopicId());
        replyInfo.setContent(param.getContent().trim());
        replyInfo.setDestId(param.getDestId());
        replyInfo.setFatherId(param.getFatherId());
        replyInfo.setCreateTime(TimeUtils.getTimeSecond());
        
        // 保存评论记录
        int ret  = moodService.saveReply(replyInfo);
        if (ret < 0)
        {
            return ApiResult.failed(10, "发布失败");
        }

        //发送短信通知
        if (param.getUserInfo().getType() == Constant.ACCOUNT_TYPE_USER)
        {
            SmsUtils.sendManageNotice("用户" + param.getUserId() + "评论了心情");
        }

        return ApiResult.success("提交成功，请等待审核"); 
    }
    
    @ApiOperation("获取心情详情")
    @PostMapping("/getDetail")
    public ApiResult<MoodDetailVO> getDetail(@RequestBody @Valid MoodGetDetailParam param) {
        MoodTopicInfoDTO dto  = moodService.getDetailByTopicId(param.getTopicId());
        if (dto == null)
        {
            return ApiResult.failed(10, "该心情已不可查看");
        }

        UserInfoVO userInfo;
        MoodTopicInfoVO topicInfo;
        userInfo   = BeanUtil.copyProperties(dto, UserInfoVO.class);
        userInfo.setType(dto.getUserType());
        topicInfo  = BeanUtil.copyProperties(dto, MoodTopicInfoVO.class);
        topicInfo.setData(JSONUtil.parseObj(dto.getContent()));

        List<MoodReplyInfoDTO> dtoList  = moodService.getReplyList(param.getUserId(), param.getTopicId(), 0, Constant.REPLY_LIST_ALL, 0);
        List<MoodReplyVO> voList  = new ArrayList<>();
        for (MoodReplyInfoDTO reply : dtoList) {
            MoodReplyVO vo  = new MoodReplyVO();
            vo.userInfo  = new UserInfoVO();
            vo.replyInfo  = new MoodReplyVO.ReplyInfoVO();

            BeanUtil.copyProperties(reply, vo.userInfo);
            BeanUtil.copyProperties(reply, vo.replyInfo);

            voList.add(vo);
        }

        MoodDetailVO vo  = new MoodDetailVO();
        vo.setReplayList(voList);
        vo.setUserInfo(userInfo);
        vo.setTopicInfo(topicInfo);

        return ApiResult.success(vo);
    }

    @ApiOperation("获取主题列表")
    @PostMapping("/getTopicList")
    public ApiResult<Object> getTopicList(@RequestBody @Valid MoodGetTopicListParam param) {
        //未登录只能查看第一页
        if ((param.getPage() > 0) || (param.getType() == Constant.MOOD_LIST_FANS) || (param.getType() == Constant.MOOD_LIST_MINE))
        {
            if ((param.getUserId() == null) || (param.getToken() == null))
            {
                return ApiResult.failed(ApiCodeEnum.NEED_LOGIN);
            }
        }

        long userId  = (param.getUserId() == null) ? 0 : param.getUserId();
        List<MoodTopicInfoDTO> dtoList  = moodService.getTopicList(userId, param.getType(), (param.getGroupId() == null) ? 0 : param.getGroupId(), param.getPage());
        List<MoodTopicListVO> voList  = new ArrayList<>();
        for (MoodTopicInfoDTO data : dtoList) {
            MoodTopicListVO vo  = new MoodTopicListVO();
            vo.userInfo   = BeanUtil.copyProperties(data, UserInfoVO.class);
            vo.userInfo.setType(data.getUserType());
            vo.topicInfo  = BeanUtil.copyProperties(data, MoodTopicInfoVO.class);
            vo.topicInfo.setData(JSONUtil.parseObj(data.getContent()));

            voList.add(vo);
        }

        JSONObject json  = new JSONObject();
        json.set("topicList", voList);

        return ApiResult.success(json);
    }

    @ApiOperation("获取评论列表")
    @PostMapping("/getReplyList")
    public ApiResult<Object> getReplyList(@RequestBody @Valid MoodGetReplyListParam param) {
        List<MoodReplyInfoDTO> dtoList  = moodService.getReplyList(param.getUserId(), param.getTopicId(), param.getFatherId(), param.getType(), param.getPage());
        List<MoodReplyVO> voList  = new ArrayList<>();
        if (dtoList != null)
        {
            for (MoodReplyInfoDTO reply : dtoList) {
                MoodReplyVO vo  = new MoodReplyVO();
                vo.userInfo  = new UserInfoVO();
                vo.replyInfo  = new MoodReplyVO.ReplyInfoVO();
    
                BeanUtil.copyProperties(reply, vo.userInfo);
                BeanUtil.copyProperties(reply, vo.replyInfo);

                voList.add(vo);
            }
        }

        JSONObject json  = new JSONObject();
        json.set("replyList", voList);

        return ApiResult.success(json);
    }

    @ApiOperation("隐藏主题")
    @PostMapping("/hideTopic")
    public ApiResult<Object> hideTopic(@RequestBody @Valid MoodHideTopicParam param) {
        MoodTopicInfo topicInfo  = moodService.getTopicById(param.getTopicId());
        if (topicInfo == null)
        {
            return ApiResult.failed(10, "当前主题不存在");
        }

        if (!topicInfo.getUserId().equals(param.getUserId()))
        {
            return ApiResult.failed(10, "权限不足");
        }

        if (param.getAction() == Constant.USER_ACTION_CANCEL)
        {
            if (topicInfo.getIsValid() == Constant.DATA_STATUS_DISABLE)
            {
                return ApiResult.failed(10, "该主题已删除");
            }

            //取消隐藏
            topicInfo.setStatus(Constant.DATA_STATUS_ENABLE);
        }
        else
        {
            if (topicInfo.getStatus() == Constant.DATA_STATUS_DISABLE)
            {
                return ApiResult.failed(10, "该主题当前不可隐藏");
            }

            //隐藏
            topicInfo.setStatus(Constant.DATA_STATUS_HIDDEN);
        }
        
        int ret  = moodService.setTopicById(topicInfo);
        if (ret < 0)
        {
            return ApiResult.failed(10, "更新主题失败");
        }

        return ApiResult.success();
    }

    @ApiOperation("删除主题")
    @PostMapping("/delTopic")
    public ApiResult<Object> delTopic(@RequestBody @Valid MoodDelTopicParam param) {
        MoodTopicInfo topicInfo  = moodService.getTopicById(param.getTopicId());
        if (topicInfo == null)
        {
            return ApiResult.failed(10, "当前主题不存在");
        }

        if (!topicInfo.getUserId().equals(param.getUserId()))
        {
            return ApiResult.failed(10, "权限不足");
        }

        if (topicInfo.getIsValid() == Constant.DATA_STATUS_DISABLE)
        {
            return ApiResult.success();
        }
        
        //删除云存文件
        TopicTypeData data  = BeanUtil.copyProperties(JSONUtil.parseObj(topicInfo.getContent()), TopicTypeData.class);
        delCloudStorage(topicInfo.getType(), topicInfo.getUserId(), data);
        
        //更新主题状态
        topicInfo.setIsValid(Constant.DATA_STATUS_DISABLE);
        moodService.setTopicById(topicInfo);

        return ApiResult.success();
    }

    @ApiOperation("删除评论")
    @PostMapping("/delReply")
    public ApiResult<Object> delReply(@RequestBody @Valid MoodDelReplyParam param) {
        MoodReplyInfo replyInfo  = moodService.getReplyById(param.getReplyId());
        if (replyInfo == null)
        {
            return ApiResult.failed(10, "当前评论不存在");
        }

        if (!replyInfo.getUserId().equals(param.getUserId()))
        {
            return ApiResult.failed(10, "权限不足");
        }

        if (replyInfo.getIsValid() == Constant.DATA_STATUS_DISABLE)
        {
            return ApiResult.success();
        }

        //更新评论信息
        replyInfo.setIsValid(Constant.DATA_STATUS_DISABLE);
        moodService.setReplyById(replyInfo);

        return ApiResult.success();
    }

    @ApiOperation("语音转文字")
    @PostMapping("/translate")
    public ApiResult<MoodTransInfo> translate(@RequestBody @Valid MoodTranslateParam param) {
        MoodTransInfo transInfo  = moodService.getTransByTopicId(param.getTopicId());
        if (transInfo != null)
        {
            return ApiResult.success(transInfo);
        }

        MoodTopicInfo topicInfo  = moodService.getTopicById(param.getTopicId());
        if (topicInfo == null)
        {
            return ApiResult.failed(10, "当前主题不存在");
        }

        if (topicInfo.getType() != Constant.MOOD_TYPE_ONLY_AUDIO)
        {
            return ApiResult.failed(-10, "心情类型错误");
        }

        //语音转译
        transInfo  = new MoodTransInfo();
        transInfo.setTopicId(param.getTopicId());
        transInfo.setAudioUri("语音文件名");
        transInfo.setContent("语音转文字内容， topicId=" + param.getTopicId());

        //保存转译结果
        moodService.saveTransContent(transInfo);

        return ApiResult.success(transInfo);
    }

    @ApiOperation("获取用户的主题列表")
    @PostMapping("/getTopicByUser")
    public ApiResult<Object> getTopicByUser(@RequestBody @Valid MoodGetUserTopicParam param) {
        int isSelf  = (param.getUserId().equals(param.getDestId())) ? 1 : 0;
        List<MoodTopicInfo> topicList  = moodService.getTopicByUser(param.getDestId(), param.getPage(), isSelf);
        List<MoodTopicInfoVO> voList  = new ArrayList<>();
        
        for (MoodTopicInfo topic : topicList) {
            MoodTopicInfoVO vo  = BeanUtil.copyProperties(topic, MoodTopicInfoVO.class);

            vo.setData(JSONUtil.parseObj(topic.getContent()));
            voList.add(vo);
        }

        JSONObject json  = new JSONObject();
        json.set("topicList", voList);

        return ApiResult.success(json);
    }

    @ApiOperation("举报心情")
    @PostMapping("/report")
    public ApiResult<Object> report(@RequestBody @Valid MoodReportParam param) {
        userService.attachBlock(param.getUserId(), param.getDestId());
        return ApiResult.success("感谢您的举报，我们将立即核实处理");
    }
}
